package com.hcc.repository.gen.metadata;

import com.hcc.repository.gen.config.GlobalConfig;
import com.hcc.repository.gen.constants.GenerateDateType;
import com.hcc.repository.gen.model.ColumnMetadata;
import com.hcc.repository.gen.model.TableMetadata;

import javax.sql.DataSource;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * MetadataQuery
 *
 * @author hushengjun
 * @date 2023/9/28
 */
public interface MetadataQuery {

    void setDataSource(DataSource dataSource);

    default TableMetadata buildTableMetadata(String tableName, GlobalConfig globalConfig) {
        throw new UnsupportedOperationException();
    }

    default List<TableMetadata> buildTableMetadata(List<String> tableNames, GlobalConfig globalConfig) {
        return tableNames.stream()
                .map(t -> {
                    TableMetadata tableMetadata = this.buildTableMetadata(t, globalConfig);
                    if (tableMetadata.getGlobalConfig() == null) {
                        tableMetadata.setGlobalConfig(globalConfig);
                    }
                    return tableMetadata;
                })
                .collect(Collectors.toList());
    }

    default void changeJavaType(GlobalConfig globalConfig, ColumnMetadata columnMetadata) {
        GenerateDateType generateDateType = globalConfig.getEntityConfig().getGenerateDateType();
        if (GenerateDateType.JAVA8_TIME.equals(generateDateType)) {
            switch (columnMetadata.getColumnType().toLowerCase()) {
                case "datetime":
                case "timestamp":
                    columnMetadata.setJavaType(LocalDateTime.class);
                    break;
                case "date":
                    columnMetadata.setJavaType(LocalDate.class);
                    break;
                case "time":
                    columnMetadata.setJavaType(LocalTime.class);
                    break;
            }
        } else if (GenerateDateType.UTIL_DATE.equals(generateDateType)) {
            switch (columnMetadata.getColumnType().toLowerCase()) {
                case "datetime":
                case "timestamp":
                case "date":
                case "time":
                    columnMetadata.setJavaType(Date.class);
                    break;
            }
        }
        if (BigInteger.class.equals(columnMetadata.getJavaType())) {
            columnMetadata.setJavaType(Long.class);
        }
    }

}
